<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <link rel="stylesheet" type="text/css" media="screen" href="../../css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="../../css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="../../layui/css/layui.css">
    <style>
        .loading {
            width: 70px;
            height: 70px;
            position: absolute;
            left: 50%;
            top: 200px;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
<body>
<!-- 树形控件组件 -->
<div style="position:absolute; top:0; left:0; width:20%; height:100%; background-color:rgba(0,0,0.0.1)">
    <button id="editTree" class="layui-btn" style="float: right;"></button>
    <div id="spaceTree" style="float: left; width: 100%;"></div>
</div>
<div id="contentDiv" style="margin-left:20%; height:100%; ">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
        <header style="height: 100%">
            <div align="left">
                <table style="width: 100%">
                    <tr>
                        <td>
                            <form class="form-inline" onsubmit="return false">
                                <div class="form-group">
                                    设备标识：
                                    <input id="deviceSN" type="text" class="form-control" placeholder="设备标识">
                                    设备名称：
                                    <input id="deviceName" type="text" class="form-control" placeholder="设备名称">
                                    <input id="treeData" type="hidden" class="form-control" placeholder="树Id">
                                    <button id="searchBt" class="layui-btn layui-btn-sm"><i
                                            class="layui-icon">&#xe615;</i>搜索
                                    </button>
                                    <button id="delBt" class="layui-btn layui-btn-sm"><i
                                            class="layui-icon">&#xe615;</i>删除设备
                                    </button>
                                    <button id="addBtn" class="layui-btn layui-btn-sm"><i
                                            class="layui-icon">&#xe615;</i>添加设备
                                    </button>
                                </div>
                            </form>
                        </td>
                        <td align="right">
                            <button class="layui-btn layui-btn-sm" id="getDeviceInfo">
                                <i class="layui-icon">&#xe608;</i> 获取平台设备
                            </button>
                        </td>
                    </tr>
                </table>
            </div>
        </header>

        <div>
            <div class="widget-body no-padding">
                <table id="dt-table" class="table table-striped table-bordered table-hover" style="width:100%">
                    <thead>
                    <tr>
                    </tr>
                    <tr>
                        <th class='th'><input type="checkbox" class="checkall"/></th>
                        <th>设备标识</th>
                        <th>设备名称</th>
                        <th>设备类型</th>
                        <th>温度</th>
                        <th>湿度</th>
                        <th>开关操作</th>
                    </tr>
                    </thead>
                    <tbody style="position: relative;">
                    <img id="loadingImg" src="../../img/loading/loading.png"
                         class="layui-anim layui-anim-rotate layui-anim-loop loading"
                    >
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>


<script type="text/javascript" src="../../js/libs/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="../../js/jq.js"></script>
<script type="text/javascript" src="../../js/plugin/datatables/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="../../js/plugin/datatables/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="../../js/my/permission.js"></script>
<script type="text/javascript" src="../../layui/layui.js"></script>
<script type="text/javascript" src="../../js/dict.js"></script>
<script type="text/javascript">
    layui.use(['layer'], function () {
        var layer = layui.layer;
    });
    var userStatus = showDictSelect("status", "userStatus", true);

    var pers = checkPermission();

    $('#loadingImg').hide()

    var example;

    function init() {

        example =
            $('#dt-table').DataTable({
                "searching": false,
                "processing": false,
                "serverSide": true,
                "language": {
                    "url": "/js/plugin/datatables/Chinese.lang"
                },
                "ajax": {
                    "url": "/device/deviceList",
                    "type": "get",
                    "data": function (d) {
                        d.sn = $('#deviceSN').val();
                        d.name = $('#deviceName').val();
                        d.treeData = $('#treeData').val();
                    },
                    "error": function (xhr, textStatus, errorThrown) {
                        var msg = xhr.responseText;
                        console.log(msg)
                    }
                },
                "dom": "<'dt-toolbar'r>t<'dt-toolbar-footer'<'col-sm-10 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-10' p v>>",
                "columns": [
                    {"data": null, "defaultContent": ""},
                    {"data": "iotId", "defaultContent": ""},
                    {"data": "name", "defaultContent": ""},
                    {"data": "iotType", "defaultContent": ""},
                    {"data": "dataTemperature1", "defaultContent": ""},
                    {"data": "dataMoisture1", "defaultContent": ""},
                    {
                        "data": "",
                        "defaultContent": "",
                        "orderable":false,
                        "render": function (data, type, row) {
                            console.log(row)
                            var typeId = row["typeId"];
                            var html = "";
                            if(typeId == '07cb95502326de2376339141372ef35c9' || typeId == "0a0e80c8720c2b3775f1bdf13ca6d4768" || typeId == "0f3f6e1c72e3a7a13dda206ee857958e4"){
                                var id = '"' +row['iotId']+ '"';
                                html += "<a href='javascript:void(0);' onclick='openIot("+ id + ")'  class='delete btn btn-default btn-xs'  ><i class='fa fa-times'></i> 开启</a>"
                                html += "<a href='javascript:void(0);' onclick='closeIot("+ id + ")'  class='up btn btn-default btn-xs'><i class='fa fa-arrow-up'></i> 关闭</a>"
                            }
                            return html;
                        }
                    },
                ],
                "columnDefs": [
                    {
                        'targets': 0,
                        'searchable': false,
                        'orderable': false,
                        'className': 'dt-body-center',
                        'render': function (data, type, row, meta) {
                            if (row.isSelected == 1) {
                                return '<input type="checkbox" class="checkchild" onclick="childClick(this)" checked="checked" value="' + row.id + '" />'
                            }
                            return '<input type="checkbox" class="checkchild" onclick="childClick(this)" value="' + row.id + '" />'
                        }
                    }]
            });
    }

    function openIot(id){
        console.log("open==="+id)
        $.ajax({
            url: '/device/updateDeviceStates',
            type: 'GET',
            dataType: 'json',
            data: {
                deviceId: id,
                status: 1
            },
            success: function(res){
                alert("已经打开")
            },
            error: function(res){
                hideLoading()
            }
        });
    }

    function closeIot(id){
        console.log("close==="+id)
        $.ajax({
            url: '/device/updateDeviceStates',
            type: 'GET',
            dataType: 'json',
            data: {
                deviceId: id,
                status: 0
            },
            success: function(res){
                alert("已经关闭")
            },
            error: function(res){
                hideLoading()
            }
        });
    }

    $("#searchBt").click(function () {
        example.ajax.reload();
    });

    $("#delBt").click(function () {
        let list = $('#dt-table').DataTable().$('input[type=checkbox]:checked')
        let deviceIdList = $.map(list, x => x.defaultValue).toString()
        let treeData = $('#treeData').val();
        if (treeData == "" || deviceIdList.length == 0) {
            alert("请选择对应空间，以及对应设备！");
        } else {
            $.ajax({
                url: '/space/delSpaceDevice',
                type: 'GET',
                dataType: 'json',
                data: {
                    spaceId: treeData,
                    deviceIds: deviceIdList
                },
            });

            example.ajax.reload();
        }
    });

    $("#getDeviceInfo").click(function () {
        $.ajax({
            url: '/device/getStatus',
            type: 'GET',
            dataType: 'json',
            beforeSend: function () {
                showLoading()
            },
            success: function (res) {
                hideLoading()
            },
            error: function (res) {
                hideLoading()
            }
        });
    });

    function showLoading() {
        $('#loadingImg').show(500)
    }

    function hideLoading() {
        $('#loadingImg').hide()
    }

    init();

    layui.use('layer', function () {
        var layer = layui.layer;

        function open() {
            layer.open({
                type: 1,
                title: '添加设备',
                content: `
                    <div>
                        <div class="widget-body no-padding">
                            <table id="add-dt-table" class="table table-striped table-bordered table-hover" style="width:100%">
                                <thead>
                                <tr>
                                </tr>
                                <tr>
                                    <th class='th'><input type="checkbox" /></th>
                                    <th>设备标识</th>
                                    <th>设备名称</th>
                                    <th>设备类型</th>
                                    <th>温度</th>
                                    <th>湿度</th>
                                    <th>电流</th>
                                    <th>功率</th>
                                    <th>电量</th>
                                </tr>
                                </thead>
                                <tbody style="position: relative;">
                                </tbody>
                            </table>
                        </div>
                    </div>
                    `,
                area: ['1000px', '630px'],
                btn: ['取消', '添加'],
                btn1: function (index) {
                    layer.close(index)
                },
                btn2: function () {
                    //执行添加操作
                    let list = $('#add-dt-table').DataTable().$('input[type=checkbox]:checked')
                    let deviceIdList = $.map(list, x => x.defaultValue).toString()
                    let treeData = $('#treeData').val();
                    console.log(deviceIdList, treeData)
                    if (treeData == "" || deviceIdList.length == 0) {
                        alert("请选择对应空间，以及对应设备！");
                    } else {
                        $.ajax({
                            url: '/space/addSpaceDevice',
                            type: 'GET',
                            dataType: 'json',
                            data: {
                                spaceId: treeData,
                                deviceIds: deviceIdList
                            },
                        });
                    }
                    example.ajax.reload();
                }
            })
        }

        $('#addBtn').click(() => {
            open()
            example =
                $('#add-dt-table').DataTable({
                    "searching": false,
                    "processing": false,
                    "serverSide": true,
                    "language": {
                        "url": "/js/plugin/datatables/Chinese.lang"
                    },
                    "ajax": {
                        "url": "/device/getUnableDevice",
                        "type": "get",
                        "data": function (d) {
                            d.sn = $('#deviceSN').val();
                            d.name = $('#deviceName').val();
                            d.treeData = $('#treeData').val();
                        },
                        "error": function (xhr, textStatus, errorThrown) {
                            var msg = xhr.responseText;
                            console.log(msg)
                        }
                    },
                    "dom": "<'dt-toolbar'r>t<'dt-toolbar-footer'<'col-sm-10 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-10' p v>>",
                    "columns": [
                        {"data": null, "defaultContent": ""},
                        {"data": "iotId", "defaultContent": ""},
                        {"data": "groupName", "defaultContent": ""},
                        {"data": "iotType", "defaultContent": ""},
                        {"data": "dataTemperature1", "defaultContent": ""},
                        {"data": "dataMoisture1", "defaultContent": ""},
                        {"data": "dataElectricity1", "defaultContent": ""},
                        {"data": "dataPowers1", "defaultContent": ""},
                        {"data": "dataQuantity1", "defaultContent": ""},
                    ],
                    "columnDefs": [
                        {
                            'targets': 0,
                            'searchable': false,
                            'orderable': false,
                            'className': 'dt-body-center',
                            'render': function (data, type, row, meta) {
                                if (row.isSelected == 1) {
                                    return '<input type="checkbox" class="checkchild" onclick="childClick(this)" checked="checked" value="' + row.id + '" />'
                                }
                                return '<input type="checkbox" class="checkchild" onclick="childClick(this)" value="' + row.id + '" />'
                            }
                        }]
                });
        })
    });
</script>


<!--空间树组件js-->
<script>
    function renderTree(data) {
        let isEdit = false
        $('#editTree').text(isEdit ? '保存树型结构' : '编辑树形结构')

        layui.use('tree', function () {
            let tree = layui.tree;
            let treeRender = tree.render({
                elem: '#spaceTree',
                data: data,
                id: 'spaceTree',
                click: function (obj) {
                    console.log(obj.data.id); //得到当前点击的节点数据
                    $('#treeData').val(obj.data.id);
                    example.ajax.reload();
                },
            })

            //点击编辑树形结构
            $('#editTree').on('click', function () {
                isEdit = !isEdit
                $('#editTree').text(isEdit ? '保存树型结构' : '编辑树形结构')

                if (isEdit) {
                    tree.reload('spaceTree', {
                        edit: ['add', 'update', 'del'],
                        operate: function (obj) {
                            var type = obj.type; //得到操作类型：add、edit、del
                            var data = obj.data; //得到当前节点的数据
                            var elem = obj.elem; //得到当前节点元素
                            var parentId = -1;

                            //Ajax 操作
                            console.log(data);
                            if (type == "update") {
                                $.ajax({
                                    type: "get",
                                    url: "/space/editSpaceName",
                                    dataType: 'json',
                                    data: {
                                        "spaceId": data.id,
                                        "spaceName": data.title
                                    },
                                })
                            }
                            if (type == "add") {
                                parentId = data.id;
                                $.ajax({
                                    type: "get",
                                    url: "/space/addSpace",
                                    dataType: 'json',
                                    data: {
                                        "parentId": parentId,
                                        "spaceName": '未命名'
                                    },
                                    success: function (data) {
                                        loadtree();
                                    }
                                })
                                parentId = -1;
                            }
                            if (type == "del") {
                                $.ajax({
                                    type: "get",
                                    url: "/space/delSpace",
                                    dataType: 'json',
                                    data: {
                                        "spaceId": data.id,
                                    },
                                })
                            }

                        }
                    })
                } else {
                    $.ajax({
                        type: "get",
                        url: "/space/spaceList",
                        dataType: 'json',
                        success: function (data) {
                            tree.reload('spaceTree', {
                                data: data,
                                edit: false
                            })
                        }
                    })
                }
            })
        })
    }


    function loadtree() {
        $.ajax({
            type: "get",
            url: "/space/spaceList",
            dataType: 'json',
            success: function (data) {
                renderTree(data);
            }
        })
    }

    loadtree();
</script>
</body>
</html>

